import wx from 'weixin-js-sdk';
import $ from 'jquery';

export default {
	getWxconfig(self, wxApi, callback) {
		self.httptool.ajaxPost(self.apis.getWxconfig + "?url=" + encodeURIComponent(window.location.href.split('#')[0]), null, function(res) {
			wxConfig(res, wxApi, callback);
		});
	},
	share(self, title, content, callback) {
		let params = {};
		params.WechatUrl = encodeURIComponent(window.location.href.split('#')[0]);

		self.httptool.ajaxAsyncBasePost(self.apis.getWxConfig, params, function(res) {
			wxConfig(res, ["onMenuShareAppMessage", "onMenuShareTimeline"], function(wx) {
				var obj = {
					title: title ? title : '一善根1', //标题
					desc: content ? content : "大型网络电商平台,时尚发艺交流社区", //描述
					link: getShareUrl(),
					imgUrl: 'http://www.touhanggo.com/hds/Mobile/Content/imgs/logo.jpeg'
				};
				wx.onMenuShareAppMessage({
					title: obj.title, // 分享标题
					desc: obj.desc, // 分享描述
					imgUrl: obj.imgUrl, // 分享图标
					link: obj.link
				});
				wx.onMenuShareTimeline({
					title: obj.title, // 分享标题
					desc: obj.desc, // 分享描述
					imgUrl: obj.imgUrl, // 分享图标
					link: obj.link
				});
			});
		});
	},
	isInWeixin() {
		var ua = navigator.userAgent.toLowerCase();
		var isWeixin = ua.indexOf('micromessenger') != -1;
		if(isWeixin) {
			return true;
		} else {
			return false;
		}
	},
	pay(self, type, tradeNo, paySuccess) {

		let params = '?outTradeNo=' + tradeNo + '&openid=' + sessionStorage.getItem('openid');
		let url_;
		if(type == 2) {
			url_ = self.apis.payVip;
		} else {
			url_ = self.apis.pay;
		}
		self.httptool.ajaxPost(url_ + params, null, function(res) {
//						alert(JSON.stringify(res.data));
			wx.chooseWXPay({
				timestamp: res.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
				nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位
				package: res.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
				signType: "MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: res.data.paySign, // 支付签名
				success: function(res) {
					if(res.errMsg == "chooseWXPay:ok") {
						if(paySuccess) {
							paySuccess(1);
						}
					}
				},
				cancel: function(res) {
					//支付取消
					paySuccess(0);
				}
			});
		}, function(res) {});
	},
	getAccessToken(self, callback) {
//		sessionStorage.setItem("authToken", 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhcGlzIiwiaWF0IjoxNTMzMjc5NjMyLCJzdWIiOiJ7XCJzaWRcIjpcIjUzYTFlNWFjMjkwYTRhYTZiZGYxOThlYmEyNzdiODY2XCJ9IiwiZXhwIjoxNTMzMjk3NjMyfQ.MFo5LpdPzW5IxshvQ9c83qrsPCNyKj74X3epjvGfcEA');
//		sessionStorage.setItem("customerId", '5ad641f332754cecb61574323741fd9d');
//		sessionStorage.setItem("nickname", '无极野风');
		let token = sessionStorage.getItem("authToken");
		let customerId = sessionStorage.getItem("customerId");
		if(token && customerId) {
			if(callback) {
				callback();
			}
			return;
		}
		var code = getcode();
		if(code) {
			self.httptool.ajaxPost("wechat/login", {
				code
			}, function(d) {
				if(d.data != null) {
					var data = d.data;
					//alert(JSON.stringify(data));
					sessionStorage.setItem("authToken", data.token);
					sessionStorage.setItem("openid", data.customer.openid);
					sessionStorage.setItem("customerId", data.customer.id);
					sessionStorage.setItem("nickname", data.customer.nickName);
					sessionStorage.setItem("headimg", data.customer.headimg);

					if(callback) {
						callback();
					}
				}
			});
		}
	}
}

function getShareUrl() {
	let url = window.location.href.toLowerCase();
	let reg = /\?code=.*#\//gi;
	url = url.replace(reg, '#/');
	url = url.replace('?from=singlemessage#/', '#/');
	if(url.indexOf('&customerid=') > -1) {
		let index = url.indexOf('&customerid=');
		url = url.substring(0, index);
	}

	if(url.indexOf('?') > -1) {
		url = url + '&customerId=' + sessionStorage.getItem("customerId");
	} else {
		url = url + '?customerId=' + sessionStorage.getItem("customerId");
	}
	return url;
}

function wxConfig(cfg, wxApi, callback) {
	if(!cfg || !cfg.data) {
		alert("获取微信配置失败");
	}
	wx.config({
		debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		appId: cfg.data.appId, // 必填，公众号的唯一标识
		timestamp: cfg.data.timestamp, // 必填，生成签名的时间戳
		nonceStr: cfg.data.nonceStr, // 必填，生成签名的随机串
		signature: cfg.data.signature, // 必填，签名，见附录1
		jsApiList: wxApi // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
	});
	wx.ready(function() {
		if(callback) {
			callback(wx);
		}
	});
}

function getcode() {
	var code = getQueryString("code");

	if(!code) {
		var obj = {
			appid: "wx4e9bf05cb04e7596",
			redirect_uri: "",
			response_type: "code",
			scope: "snsapi_userinfo",
			state: "10"
		};
		var getcodeparas = $.extend(obj, {
			redirect_uri: encodeURIComponent(window.location.href)
		});
		window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" + perapara(getcodeparas) + "#wechat_redirect";
	} else {
		return code;
	}
}

function getQueryString(val) {
	var reg = new RegExp("(^|&)" + val + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);

	if(r != null) return unescape(r[2]);
	return null;
}

function perapara(objvalues, isencode) {
	var parastring = "";
	for(var key in objvalues) {
		isencode = isencode || false;
		if(isencode) {
			parastring += (key + "=" + encodeURIComponent(objvalues[key]) + "&");
		} else {
			parastring += (key + "=" + objvalues[key] + "&");
		}
	}
	parastring = parastring.substr(0, parastring.length - 1);
	return parastring;
}